package com.github.hgkmail.hello.leetcode101.pointer.tree;

import com.github.hgkmail.hello.leetcode101.base.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class LC102BinaryTreeLevelOrderTraversal {

    public List<List<Integer>> levelOrder(TreeNode root) {
        //base
        if (root==null) {
            return new ArrayList<>();
        }
        //bfs
        int level=0; //扩大的层次，即最短路径长度
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> aCase = new ArrayList<>();

        while (!queue.isEmpty()) { //bfs循环一：队列不为空
            level++;
            //一层的节点数
            int len=queue.size();
            while (len>0) { //bfs循环二：遍历一层的节点
                len--;
                TreeNode node = queue.poll();
                aCase.add(node.val);
                if (node.left!=null) {
                    queue.offer(node.left);
                }
                if (node.right!=null) {
                    queue.offer(node.right);
                }
            }
            res.add(aCase);
            aCase = new ArrayList<>();
        }

        return res;
    }

    public static void main(String[] args) {
        TreeNode a = new TreeNode(15, null, null);
        TreeNode b = new TreeNode(7, null, null);
        TreeNode c = new TreeNode(20, a, b);
        TreeNode d = new TreeNode(9, null, null);
        TreeNode e = new TreeNode(3, d, c);
        System.out.println(new LC102BinaryTreeLevelOrderTraversal().levelOrder(e));
    }
}
